
import os
import time

import pandas as pd
from docx import Document

import utils
import docwriter

def nutrition_add(doc, nutrition_df):

    nutrition_df.columns = ['Nutrients', 'Values', 'Unit of Measure']
    docwriter.docx_add_table(doc, nutrition_df, [7, 2.5, 5])


def bkd_nutrition(df):

    productinfo = {"Product Code": df.iloc[0, 0],
                   "Product Name": df.iloc[0, 1],
                   'Document type': "Nutrition Facts",
                   "Doc date": time.strftime("%b %Y", time.localtime())}

    try:
        header_template = utils.generate_Header(productinfo)
        doc = Document(header_template)
    except Exception as e:
        print(e)
    
    nutrition_df = df.loc[df["Type"] == "Nutrition Facts", [
        "Item", "Target", "Method"]].reset_index(drop=True)
    
    nutrition_df,remain_item = sort_nf(nutrition_df)
    print(f'不在清单中的营养成分：{remain_item}')
    #print(nutrition_df)
    nutrition_add(doc, nutrition_df)
    #except Exception as e:
        #print(e)
    save_path = utils.set_save_path(productinfo)
    filename = os.path.join(save_path, os.path.split(header_template)[-1])
    doc.save(filename)
    return filename,remain_item
    # doc_file_list.append(filename)


def sort_nf(df: pd.DataFrame) -> pd.DataFrame:
    nf_list = ['Energy',
               'Protein',
               'Phycocyanin',
               'Total Fat',
               'Saturated Fat',
               'Trans Fat',
               'Cholesterol',
               'Total Carbohydrates',
               'Dietary Fiber',
               'Sugar',
               'Sodium',
               'Calcium',
               'Potassium',
               'Iron']
    
    nf_index=[df[df['Item'].str.contains(i,case=False)].index[0] 
                for i in nf_list
                if len(df[df['Item'].str.contains(i,case=False)].index)!=0]
    remain_index = list(set(df.index) - set(nf_index))
    remain_item = df.loc[remain_index, "Item"].unique()
    new_index = nf_index + remain_index
    df = df.loc[new_index,:]
    df.reset_index(drop=True,inplace=True)
    return df,remain_item

def write_nf(productcode):
    remain_item = []
    df_raw = utils.validate_product_info()
    df = df_raw.copy()
    file_ready = True
    if productcode in df["Product Code"].unique():
        df = df[df["Product Code"] == productcode]
        df = df.reset_index(drop=True)
        # file_ready = utils.validate_df(df)
        filename,remain_item = bkd_nutrition(df)
    else:
        print("!Error. No such code!")

    return filename,remain_item


if __name__ == "__main__":
    productcode = "SR4000"
    filename = write_nf("SR0297")

